package com.sh.sh_ai_agent.chatmemory;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import org.objenesis.strategy.StdInstantiatorStrategy;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.stringtemplate.v4.ST;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: sh
 * @Version 1.0
 * @Description: 基于文件的聊天记忆实现
 */
public class FileBaseChatMemory implements ChatMemory {

    private final String BASE_DIR;

    private static final Kryo kryo = new Kryo();

    static {
        kryo.setRegistrationRequired(false);
        // 设置实例化策略
        kryo.setInstantiatorStrategy(new StdInstantiatorStrategy());
    }

    public FileBaseChatMemory(String baseDir) {
        this.BASE_DIR = baseDir;
        File file = new File(BASE_DIR);
        if (!file.exists()) {
            file.mkdir();
        }
    }


    @Override
    public void add(String conversationId, Message message) {
        saveConversation(conversationId, new ArrayList<>(List.of(message)));
    }


    @Override
    public void add(String conversationId, List<Message> messages) {
        List<Message> messageList = getOrCreateConversation(conversationId);
        messageList.addAll(messages);
        saveConversation(conversationId, messageList);
    }


    @Override
    public List<Message> get(String conversationId, int lastN) {
        List<Message> messageList = getOrCreateConversation(conversationId);
        return messageList.stream().skip(Math.max(0, messageList.size() - lastN)).toList();
    }

    @Override
    public void clear(String conversationId) {
        File conversationFile = getConversationFile(conversationId);
        if (conversationFile.exists()) {
            conversationFile.delete();
        }
    }


    /**
     * 保存会话到文件
     *
     * @param conversationId
     * @return
     */
    private void saveConversation(String conversationId, List<Message> messages) {
        File file = getConversationFile(conversationId);
        try (Output output = new Output(new FileOutputStream(file))) {
            kryo.writeClassAndObject(output, messages);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }



    /**
     * 从文件里面获取会话消息列表
     *
     * @param conversationId
     * @return
     */
    private List<Message> getOrCreateConversation(String conversationId) {
        File file = getConversationFile(conversationId);
        List<Message> messages = new ArrayList<>();
        if (file.exists()) {
            try (Input input = new Input(new FileInputStream(file))) {
                messages = (List<Message>) kryo.readClassAndObject(input);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return messages;
    }

    /**
     * 每个会话单独保存
     *
     * @param conversationId
     * @return
     */
    private File getConversationFile(String conversationId) {
        return new File(BASE_DIR, conversationId + ".kryo");
    }

}

